<%= javascript_include_tag "application" %>

<% form_for(@warehouse) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <p>
    <%= f.label :street %><br />
    <%= f.text_field :street %>
  </p>
  <p>
    <%= f.label :city %><br />
    <%= f.text_field :city %>
  </p>
  <p>
    <%= f.label :postal_code %><br />
    <%= f.text_field :postal_code %>
  </p>
  <p>
    <%= f.label :country %><br />
    <%= f.text_field :country %>
  </p>
  <p>
    <%= f.label :area %><br />
    <%= f.text_field :area %>
  </p>
<% end %>


<script type="text/javascript">
  var positions = new Array();
  var indexKey = 1;
</script>

<p>
Positions | <a href="#" onclick="{removeAllPositions(positions);}">Remove all</a>
</p>

<ul id="positions_list">
</ul>

<script type="text/javascript">
  <!-- prepopulate positions list -->
  <% @warehouse.positions.each_with_index do |position, index_key| %>
    <% product = Product.find(position.product_id) %>
    addPosition(positions, <%= index_key + 1 %>, <%= position.product_id %>, "<%= product.name %>", "<%= position.quantity %>", "<%= product.unit %>");
  <% end %>
  indexKey = positions.length + 1;
</script>


<form name="add_position_form" method="post">
  <%= label :position, :product_id, "Product" %>
  <%= select("position", "product_id", Product.find(:all).collect {|p| [ p.name, p.id ] }, { :include_blank => true }) %>

  <%= label :position, :quantity %>
  <%= text_field "position", "quantity", :size => 5 %>
  <span id="unit_field"></span>

  <input type="button" value="Add position" onclick = "
    if (validateAddPositionForm()) {
      addPositionFromForm(positions, indexKey);
	  indexKey++;
	}
  "/>
</form>

<script type="text/javascript">
  <!-- generate (product_id, unit) map -->
  var productUnitsMap = new Object();
  <% Product.all.each do |product| %>
    productUnitsMap[<%= product.id %>] = '<%= product.unit %>';
  <% end %>
  
  <!-- set initial value of the unit field -->
  setUnitField(productUnitsMap);
  
  <!-- add event listener to update unit field -->
  document.add_position_form.elements[0].onchange = function() {
    setUnitField(productUnitsMap);
  }
</script>

<p>
  <input type="button" value="Save" onclick="{
	setPositionsCookie(positions);
    document.forms[0].submit();
  }" />
</p>